/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.swapper.regexp;

import java.util.Objects;
import java.util.Random;

/**
 * The regular expression character classes node.
 * Including normal, predefined, and POSIX character classes.
 *
 * @see CharacterClasses the character classes implement.
 */
final class CharacterClassesNode extends PatternNode {
  private final int weight;
  private final CharacterClasses classes;

  /**
   * Public constructor.
   *
   * @param context the generator context.
   * @param classes the character classes.
   * @throws NullPointerException if {@code classes} is null.
   */
  public CharacterClassesNode(PatternReverser context, CharacterClasses classes) {
    super(context);
    classes.unmodifiable();
    this.classes = classes;
    this.weight = classes.weight();
  }

  /**
   * Gets the character classes.
   *
   * @return the character classes.
   */
  public CharacterClasses classes() {
    return classes;
  }

  /**
   * Gets the random weight.
   *
   * @return the random weight.
   */
  @Override
  public int weight() {
    return weight;
  }

  @Override
  public String random(Random random) {
    int index = random.nextInt(weight);
    for (CharacterRange range : classes) {
      int weight = range.weight();
      if (index > weight - 1) {
        index -= weight;
      } else {
        return CharacterHelper.codePointToString(range.offset(index));
      }
    }
    throw new IllegalStateException("Unexpected random index!");
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof CharacterClassesNode) {
      CharacterClassesNode that = (CharacterClassesNode) o;
      return weight == that.weight && Objects.equals(classes, that.classes);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hash(classes, weight);
  }
}
